package net.hzlj.platform.enterprise.service;

import android.accounts.Account;
import android.app.Service;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.SyncResult;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import net.hzlj.platform.enterprise.common.Constant;
import net.hzlj.platform.enterprise.provider.AccountProvider;
import net.hzlj.platform.enterprise.utils.ServiceUtils;


/**
 * @Description:
 * @Author: Jason Zhang
 * @Date: 2017/1/12 0012
 */

public class SyncAccountService extends Service {

    public static final String TAG = SyncAccountService.class.getSimpleName();

    private static final Object mSyncAdapterLock = new Object();
    private static AccountSyncAdapter mAccountSyncAdapter = null;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        synchronized (mSyncAdapterLock) {
            if (mAccountSyncAdapter == null) {
                mAccountSyncAdapter = new AccountSyncAdapter(getApplicationContext(), true);
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind");
        return mAccountSyncAdapter.getSyncAdapterBinder();
    }

    static class AccountSyncAdapter extends AbstractThreadedSyncAdapter {

        private Context mContext;

        public AccountSyncAdapter(Context context, boolean autoInitialize) {
            super(context, autoInitialize);
            mContext = context;
        }

        public AccountSyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
            super(context, autoInitialize, allowParallelSyncs);
        }

        @Override
        public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
            Log.i(TAG, " AccountSyncAdapter onPerformSync");
            getContext().getContentResolver().notifyChange(AccountProvider.CONTENT_URI, null, false);
            mContext.sendBroadcast(new Intent(Constant.Intent.ACTION_SOCKET_RECONNECT));
        }
    }
}
